﻿using System.Collections.Generic;
using Gumini.JulaDB.Data;
using Gumini.JulaDB.Expressions;

namespace Gumini.JulaDB.Engine
{
    using GroupKey = CompositeKey<TypedValue>;

    internal class RowMapping : IEnumerable<KeyValuePair<GroupKey, List<Row>>>
    {
        private readonly Dictionary<GroupKey, List<Row>> _groupMapping;

        public RowMapping(bool emptyGroupsAreEqual)
        {
            _groupMapping = new Dictionary<GroupKey, List<Row>>(
                new GroupKey.EqualityComparer(emptyGroupsAreEqual));
        }

        public void Add(IEnumerable<TypedValue> keyValues, Row row)
        {
            var key = new GroupKey(keyValues);

            // adding the group to dictionary
            if (!_groupMapping.ContainsKey(key))
                _groupMapping.Add(key, new List<Row> { row });
            else
                _groupMapping[key].Add(row);
        }

        public void Add(IEnumerable<TypedValue> keyValues)
        {
            var key = new GroupKey(keyValues);
            _groupMapping.Add(key, new List<Row>());
        }

        public IEnumerable<Row> this[GroupKey key]
        {
            get { return _groupMapping[key]; }
        }

        public bool ContainsKey(GroupKey key)
        {
            return _groupMapping.ContainsKey(key);
        }

        public bool IsEmpty
        {
            get { return _groupMapping.Count == 0; }
        }

        public IEnumerator<KeyValuePair<GroupKey, List<Row>>> GetEnumerator()
        {
            return _groupMapping.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _groupMapping.GetEnumerator();
        }
    }
}
